package org.hank.wanandroid.ui

import android.animation.ValueAnimator
import android.os.Bundle
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.view.animation.ScaleAnimation
import android.view.inputmethod.EditorInfo
import android.widget.RelativeLayout
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.tencent.mmkv.MMKV
import kotlinx.android.synthetic.main.activity_search.*
import org.hank.commom.base.BaseActivity
import org.hank.commom.utils.KeyBoardUtil
import org.hank.commom.utils.UIUtils
import org.hank.wanandroid.R
import org.hank.wanandroid.constants.Constants
import org.hank.wanandroid.listener.OnArticleRecyclerListener
import org.hank.wanandroid.ui.widget.ArticleRecycleWidget
import org.hank.wanandroid.utils.showSnackToast
import org.hank.wanandroid.utils.showTipsDialog
import org.hank.wanandroid.viewmodel.SearchViewModel

class SearchActivity : BaseActivity(), OnArticleRecyclerListener {
    override val layoutResId: Int
        get() = R.layout.activity_search
    var isFirstLoad: Boolean = true

    val viewModel by getViewModel(SearchViewModel::class.java) {
        searchRetLiveData.observe(it) {
            totalPage = it!!.pageCount
            if (pageNum < totalPage)
                pageNum += 1
            articleRecyclerFragment.validateData(it?.datas)
            dismissRefresh()
            if (it.datas!!.size == 0)
                loadingTip.showEmpty()
            else
                loadingTip.dismiss()
        }
    }
    var articleRecyclerFragment = ArticleRecycleWidget(this)
    var pageNum = 0
    var totalPage = 1
    var initWidth = 0
    var recordList: MutableList<String> = ArrayList()
    var keyWord: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        startSearchAnima()
        ivBack.setOnClickListener { finish() }
        var record = MMKV.defaultMMKV()?.getString(Constants.SEARCH_RECORD, null)
        if (!record.isNullOrEmpty()) {
            recordList = Gson().fromJson<MutableList<String>>(
                record,
                object : TypeToken<MutableList<String>>() {}.type
            )
        }
        editText_search.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(p0: Editable?) {
                if (!editText_search.text.toString().isNotEmpty()) {
                    ivClear.visibility = View.GONE
                    clRecord.visibility = View.VISIBLE
                    smartRefresh_search.visibility = View.GONE
                    loadRecord()
                }
            }
        })
        editText_search.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                keyWord = editText_search.text!!.toString().trim { it <= ' ' }
                if (!TextUtils.isEmpty(keyWord)) {
                    for (index in 0 until recordList?.size!!) {
                        if (recordList!![index] == keyWord) {
                            recordList!!.removeAt(index)
                            break
                        }
                    }
                    recordList?.add(keyWord!!)
                    onReload()
                    articleRecyclerFragment.notifyReload()
                }
            } else {
                showSnackToast("请输入关键字")
                dismissRefresh()
                return@setOnEditorActionListener false
            }
            return@setOnEditorActionListener true
        }
        ivClear.setOnClickListener { editText_search.text = SpannableStringBuilder("") }
        tvClear.setOnClickListener {
            showTipsDialog(this, "确定清除搜索历史记录?") {
                recordList.clear()
                loadRecord()
            }
        }

        smartRefresh_search.setOnRefreshListener {
            onReload()
            articleRecyclerFragment.notifyReload()
        }
        smartRefresh_search.setOnLoadMoreListener {
            if (pageNum < totalPage) {
                search()
            } else {
                articleRecyclerFragment.validateData(null)
                smartRefresh_search.finishLoadMore()
            }
        }
        var ft = supportFragmentManager.beginTransaction()
        ft.add(R.id.frame_search, articleRecyclerFragment)
        ft.commit()
        loadRecord()
    }

    fun search() {
        if (!editText_search.text.isNullOrEmpty()) {
            viewModel.search(pageNum, editText_search.text.toString())
            ivClear.visibility = View.VISIBLE
            clRecord.visibility = View.GONE
            smartRefresh_search.visibility = View.VISIBLE
        } else {
            showTipsDialog(this, "请输入关键字!")
        }
        KeyBoardUtil.closeKeyboard(editText_search.windowToken, this)

    }

    /**
     * 开启搜索动画
     */
    fun startSearchAnima() {
        rlTop.post {
            //创建属性动画，开启属性动画监听
            var initWidth = rlTop.measuredWidth
            var left = rlTop.left - UIUtils.dip2px(this, 10f)
            var animate = ValueAnimator.ofInt(initWidth, left)
            animate.duration = 300
            animate.addUpdateListener {
                val currentValue = it.animatedValue as Int
                val params = rlTop.layoutParams as RelativeLayout.LayoutParams
                params.width = currentValue
                rlTop.layoutParams = params
                //展开软键盘，开启标签动画
                if (currentValue == left) {
                    startLabelAnim()
                    editText_search.requestFocus()
                    //展开软键盘
                    KeyBoardUtil.openKeyboard(editText_search, this)
                }
            }
            animate.start()
        }
    }

    override fun onStop() {
        super.onStop()
        MMKV.defaultMMKV()?.putString(Constants.SEARCH_RECORD, Gson().toJson(recordList))
    }

    /**
     * 展开标签
     */
    fun startLabelAnim() {
        for (index in 0 until labelsView.childCount) run {
            val view: View = labelsView.getChildAt(index)
            view.visibility = View.VISIBLE
            val aa = ScaleAnimation(0f, 1f, 0.5f, 1f)
            aa.interpolator = DecelerateInterpolator()
            aa.duration = 500
            view.startAnimation(aa)
        }
    }

    /**
     * 加载搜索tag
     */
    private fun loadRecord() {
        labelsView.setLabels(recordList) { label, _, data ->
            if (isFirstLoad) {
                label.visibility = View.GONE
            }
            data
        }
        isFirstLoad = false
        //标签的点击监听
        labelsView.setOnLabelClickListener { _, data, _ ->
            if (data is String) {
                editText_search.setText(data)
                editText_search.setSelection(data.length)
                keyWord = data
                articleRecyclerFragment.notifyReload()
                pageNum = 0
                search()
            }
        }
    }

    override fun finish() {
        super.finish()
        this.overridePendingTransition(0, R.anim.search_out_anim);
        var width = rlTop.measuredWidth
        var animate = ValueAnimator.ofInt(width, initWidth)
        animate.duration = 500
        animate.interpolator = DecelerateInterpolator()
        animate.addUpdateListener {
            val currentValue = it.animatedValue as Int
            val params = rlTop.layoutParams as RelativeLayout.LayoutParams
            params.width = currentValue
            rlTop.layoutParams = params
        }
        animate.start()
    }

    override fun onReload() {
        pageNum = 0
        loadingTip.loading()
        search()
    }

    fun dismissRefresh() {
        smartRefresh_search.finishLoadMore()
        smartRefresh_search.finishRefresh()
    }

    override fun showToast(msg: String) {
        super.showToast(msg)
        dismissRefresh()
        articleRecyclerFragment.validateData(null)
        loadingTip.showInternetError()
    }
}